﻿using AntdUI;
using System;
using System.Collections.Generic;

namespace Controls
{
    public class AlertManager
    {
        private readonly Alert alert;
        private readonly Queue<(string message, TType type)> messageQueue = new Queue<(string, TType)>();
        private readonly System.Windows.Forms.Timer throttleTimer;
        private const int ThrottleInterval = 100; // 毫秒

        public AlertManager(Alert alertControl)
        {
            alert = alertControl ?? throw new ArgumentNullException(nameof(alertControl));

            throttleTimer = new System.Windows.Forms.Timer();
            throttleTimer.Interval = ThrottleInterval;
            throttleTimer.Tick += ThrottleTimer_Tick;
        }

        public void ShowAlert(string message, TType type = TType.Info)
        {
            messageQueue.Enqueue((message, type));
            if (!throttleTimer.Enabled)
            {
                throttleTimer.Start();
            }
        }

        private void ThrottleTimer_Tick(object sender, EventArgs e)
        {
            if (messageQueue.Count > 0)
            {
                var (message, type) = messageQueue.Dequeue();
                UpdateAlertUI(message, type);
            }
            else
            {
                throttleTimer.Stop();
            }
        }

        private void UpdateAlertUI(string message, TType type)
        {
            if (alert.InvokeRequired)
            {
                alert.BeginInvoke(new Action(() => UpdateAlertUI(message, type)));
                return;
            }

            alert.Text = message;
            alert.Icon = type;
            alert.Invalidate();
        }

        public void Dispose()
        {
            throttleTimer?.Dispose();
        }
    }
}
